<template>
  <div class="dept-agent-config">
    <div class="da-info__wapper">
      <div class="da-info__content">
        <affix label="信息查询" class="da-info__search">
          <search-agent @search="searchAgentData" ref="searchAgent"></search-agent>
        </affix>
        <affix :label="$t('config.agent.searchAgentList')" class="da-info__list">
          <div class="list">
            <div class="list__wapper">
              <div class="list__title" style="margin-bottom: 0px">
                <div class="list-left__menu">
                  <span class="list__menu"
                        @click.stop="handleClick('showBatch')">
                    <i class="icon iconfont icon-beizhu"></i>{{$t('config.agent.bacthEdit')}}
                  </span>
                  <span class="list__menu" @click.stop="refrech">
                    <el-button class="icon iconfont icon-shuaxin" type="text"></el-button>{{$t('public.refresh')}}
                  </span>
                 </div>
                 <pagination class="list-right__menu" :small="true"
                            :currentPage="trunPage"
                            :count="total"
                            @turnPage="trunPages"
                            :totalPage="Math.ceil(total/10)"></pagination>
               </div>
               <agent-table :tableData = "tableData"
                           ref = "tableData"
                           @removeLock="refrech"
                           @updateUser = "updateUser"></agent-table>
            </div>
          </div>
        </affix>
      </div>
    </div>
    <leftSlide :visible.sync='slideLeft'
               :title="title"
               @saveClick="handleSaveCLick"
               @cancelClick="cancelClick"
               :showFooter="true">
      <edit-agent
                  v-if="flag === 'EditAgent'"
                  ref="recommendedPwd"
                  :agentDetail = "agentDetail"
                  @EditAgent = "editAgent"></edit-agent>
    </leftSlide>
    <bacth-edit-agent-info ref="batchEditAgentInfo1"
                           @close="close"
                           @BacthEditAgentInfo="BacthEditAgentInfo"
                           :total="total" :roles="roles"></bacth-edit-agent-info>
  </div>
</template>
<script>
  import Affix from '@/components/ui-modules/affix/Affix'
  import SearchAgent from './info/SearchAgent'
  import { deepClone, removeEmptyProperty } from '@/utils/m7Utils'
  import leftSlide from '@/components/ui-modules/newConfig/leftSlide.vue'
  import EditAgent from './info/SearchAgentListBase/EditAgent'
  import BacthEditAgentInfo from './info/SearchAgentListBase/BacthEditAgentInfo'
  import AgentTable from './info/SearchAgentListBase/AgentTable.vue'
  import Pagination from '@/components/public-modules/card/Pagination'
  export default {
    name: 'AgentConfig',
    data () {
      return {
        title: '',
        agentDetail: {},
        flag: '',
        slideLeft: false,
        licenceType: [],
        data: {
          page: 1,
          limit: 10
        },
        trunPage: 1,
        deptId: '',
        treeData: [],
        tableData: [],
        depts: [],
        roles: [],
        count: 0,
        versions: [],
        total: 0
      }
    },
    components: {
      EditAgent,
      AgentTable,
      Pagination,
      BacthEditAgentInfo,
      leftSlide,
      Affix,
      SearchAgent
    },
    methods: {
      close () {
        this.flag = ''
      },
      // 批量修改座席，成功之后刷新数据
      BacthEditAgentInfo (data) {
        this.$store.dispatch('batchUpdateUser', data)
          .then((res) => {
            if (res && res.success) {
              this.refrech()
              if (res.hasSecondaryExten) {
                this.$message({
                  message: this.$t('agentSetting.agentSetting34'),
                  type: 'success'
                })
                return
              }
              this.$message({
                message: this.$t('config.agent.bacthEditSuccess'),
                type: 'success'
              })
            }
          })
      },
      // 修改座席，成功之后刷新数据
      editAgent (data) {
        this.$store.dispatch('updateUser', data)
          .then((res) => {
            if (res && res.success) {
              this.$message({
                message: this.$t('config.agent.modifyAgentSuccess'),
                type: 'success'
              })
              this.flag = ''
              this.slideLeft = false
              this.refrech()
            }
          })
          .then(() => {
            this.refrech()
          })
      },
      /**
       * 接收子组件tableAgent传出来需要修改座席的信息,再传给子组件EditAgent进行修改
       * 参数为要修改座席的信息
       * 展示修改弹窗
       */
      updateUser (agentId) {
        let data = agentId
        this.$store.dispatch('getUserById', data)
          .then((res) => {
            if (res && res.success) {
              this.slideLeft = true
              this.title = '修改座席'
              this.flag = 'EditAgent'
              this.agentDetail = res.user
              this.$nextTick(() => {
                this.$refs.recommendedPwd.resetForm()
                this.$refs.recommendedPwd.init()
                this.$refs.recommendedPwd.updatePwd()
              })
//              this.isEdit = true
//              this.$refs.recommendedPwd.updatePwd()
            }
          })
      },
      handleSaveCLick () {
        if (this.flag === 'showBatch') {
          this.$refs.batchEditAgentInfo1.onSubmit()
        } else if (this.flag === 'EditAgent') {
          this.$refs.recommendedPwd.onSubmit()
        }
      },
      cancelClick () {
        this.flag = ''
        this.slideLeft = false
      },
      handleClick (flag) {
        this.flag = flag
        if (flag === 'showBatch') {
          this.slideLeft = false
          this.title = '批量修改'
          this.$nextTick(() => {
            this.$nextTick(() => {
              this.$refs.batchEditAgentInfo1.open()
            })
          })
        }
      },
      // 接受树组件传出来的方法搜索table数据并进行渲染
      searchAgent () {
        getTableData(this, this.data)
        .then((depts) => {
          this.total = depts.count
          this.tableData = this.dealQueryUser(depts.list)
        })
      },
      /**
       * [searchAgentData description]
       * @param  {[type]} form
       *  [description]
       * @return {[type]}     [description]
       * 根据部门Id查询相关座席
       * 当 deptId 是 'noDept' 时 查询的是未分配的部门
       */
      searchAgentData (form) {
        this.trunPage = 1
        let req = deepClone(this.data)
        if (typeof form === 'string') {
          let data = {
            page: 1,
            limit: 10
          }
          req = deepClone(data)
          req.deptId = form
          this.deptId = form
          req = removeEmptyProperty(req)
        } else {
          req = deepClone(form)
          req = removeEmptyProperty(req)
          req.deptId = this.deptId
        }
        getTableData(this, req)
        .then((resp) => {
          this.total = resp.count
          this.tableData = this.dealQueryUser(resp.list)
        })
      },
      // 由于判断繁琐抽出来的通过pID判断是不是全公司是不传方法
      searchDeptAgentData (form) {
        this.trunPage = 1
        this.$refs.searchAgent.resetFrom() // 点击部门树形的时候，重置表单
        let req = {
          page: 1,
          limit: 10
        }
        if (form.pId) {
          req.deptId = form._id
          this.deptId = form._id
        } else {
          this.deptId = ''
        }
        req = removeEmptyProperty(req)
        getTableData(this, req)
        .then((resp) => {
          this.total = resp.count
          this.tableData = this.dealQueryUser(resp.list)
        })
      },
      trunPages (page) {
        this.data = deepClone(this.$store.state.config.agentConfig.queryAgent)
        this.data.page = page
        this.data.limit = 10
        this.trunPage = page

        getTableData(this, this.data)
        .then((depts) => {
          this.total = depts.count
          this.tableData = this.dealQueryUser(depts.list)
        })
      },
      refrech () {
        this.data = this.$store.state.config.agentConfig.queryAgent
//        if (this.trunPage !== 1) {
//          this.trunPage = 1
//          return
//        }
        getTableData(this, this.data)
        .then((depts) => {
//          this.trunPage = 1
          if (depts && depts.success) {
            if (depts.list.length === 0) {
              // 算出最后一页的页数
              let page = Math.ceil(depts.count / 10)
              this.trunPages(page)
            } else {
              this.total = depts.count
              this.tableData = this.dealQueryUser(depts.list)
            }
          }
        })
      },

      getDeptName (id) {
        for (let i in this.depts) {
          if (this.depts[i]._id === id) {
            return this.depts[i].name
          }
        }
        return ''
      },
      /**
       *  需修改 状态
       * [dealQueryUser description]
       * @param  {[type]} data [description]
       * @return {[type]}      [description]
       */
      dealQueryUser (data) {
        data.forEach(item => {
          item.displayName = `${item.displayName}(${item.exten})`
          item.deptName = this.getDeptName(item.deptId) || this.$t('config.agent.notAssignedDept')
          item.parentId = item.parentId
          item.roleName = this.dealRole(item.role)
          item.mobile = item.mobile
          item.status = item.status
          item.uversion1 = this.dealLicenceType(item.uversion)
          item._id = item._id
        })
        return data
      },
      // 处理座席使用版本
      dealLicenceType (data) {
        let _value = ''
        for (let i = 0; i < this.licenceType.length; i++) {
          if (this.licenceType[i].code_value === data) {
            _value = this.licenceType[i].code_name
            break
          }
        }
        return _value
      },
      dealRole (data) {
        let arrRole = []
        for (let i in data) {
          for (let j in this.roles) {
            data[i] === this.roles[j]._id &&
            arrRole.push(this.roles[j].display_name)
          }
        }
        return arrRole.toString()
      },
      dealVersionNum () {
        let response = []
        this.$store.dispatch('queryVersionNum', {})
        .then((res) => {
          if (res && res.success) {
            response = res.uversions
            let Packages = deepClone(this.$getCache('licenceType'))
            for (let i in response) {
              for (let j = 0; j < Packages.length; j++) {
                if (response[i]._id === Packages[j].code_value) {
                  this.versions.push({
                    label: Packages[j].code_name,
                    value: response[i].count,
                    label1: `${Packages[j].code_name}licence`,
                    value1: response[i].licenceCount
                  })
                }
              }
            }
          }
        })
      }
    },
    beforeMount () {
      Promise.all([
        this.$store.dispatch('getCache', { type: 'depts' }),
        this.$store.dispatch('getCache', {type: 'roles'}),
        this.$store.dispatch('getCache', { type: 'licenceType' })
      ])
      .then(([depts, roles, licenceType]) => {
        this.roles = roles
        this.depts = depts
        this.licenceType = licenceType
      })
      .then(() => {
        getTableData(this, this.data).then((res) => {
          if (res && res.success) {
            this.total = res.count
            this.tableData = this.dealQueryUser(res.list)
          }
        })
      }).then(() => {
        this.dealVersionNum()
      })
    }
  }
  // 获取座席信息
  function getTableData (vm, data) {
    return vm.$store.dispatch('queryUser', data)
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  $width=340px
  $t-height=40px
  .icon-tixingweizhi
    box-sizx(15px)
    border 1px solid $c-main
    border-radius 8px
    color $c-main
    font-size 12px

  .da-tree__wapper
    height 100vh
    background #fff
    .da-tree__heardwapper
      border-bottom 1px solid $c-border1
      .da-tree__heard
        height $t-height
        margin 0 12px
        display flex
        justify-content space-between
        align-items center
  .da-info__wapper
    overflow-x auto
    .da-info__title
      padding 10px
      color $c-prompt
      border-bottom 1px solid $c-border1
      h3
        font-size 14px
        line-height $t-height
        margin-left 22px
    .da-info__content
      margin-top 20px
      padding-bottom 25px
      height calc(100vh - 160px)
      margin-left 15px
      overflow-y auto
      .da-info__search
        padding-bottom 4px
  .da-info__list
    .list__title
      display flex
      justify-content space-between
      align-items center
      margin-bottom 6px
  .list-left__menu
    span
      cursor pointer
  .icon
    margin-right 4px
  .list__wapper
    width 100%
    .list__title
      border 1px solid #e7e7eb
      border-bottom 0
      display flex
      align-items center
      justify-content space-between
      .list__menu
        margin-left 16px
      .iconfont
        color $c-main
</style>
